from django.db import transaction
from django.shortcuts import render
from django.utils import timezone
from django.http import HttpResponse

from myapp4.models import *


@transaction.atomic
def userinfo_trans(request):
    # 开启事务
    save_id = transaction.savepoint()
    try:
        # 保存基本信息
        d = dict(
            username="测试1",
            password='123456',
            status=1,
            createdate=timezone.now()
        )
        userbaseinfo = UserBaseInfo.objects.create(**d)
        raise  # 抛出异常
        # 保存扩展信息
        d = dict(
            username="测试1",
            truename="测试1",
            sex=0,
            salary=6555.88,
            age=35,
            status=0,
            createdate=timezone.now(),
            memo='',
            user=userbaseinfo,
        )
        userextrainfo = UserExtraInfo.objects.create(**d)
        transaction.savepoint_commit(save_id)
        msg = "新增数据成功"
        print(msg)
    except Exception as e:
        transaction.savepoint_rollback(save_id)
        msg = "新增数据失败"
        print(msg)
    return HttpResponse(msg)
